package com.bieber.smartpost.invoke.filter.filler;

import com.bieber.smartpost.invoke.FilterContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.jbeer.framework.annotation.Bean;
import com.jbeer.framework.exception.JBeerException;
import com.jbeer.framework.parser.json.JSON;
import com.jbeer.framework.utils.StringUtils;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理#{json:'tagName'[number][default:xxxxx]}占位符的参数
 * Created by bieber on 14-11-30.
 */
@Bean
public class JSONFiller extends  BasicFiller<String> {


    private static final String EXPRESSION_REGEX="'\\$[\\x20\\t\\r\\n\\f\\w\\?\\.@\\[\\]\\(\\)<=\\$'-:,\\*]+'";

    private static final Pattern JSON_FILLER_PATTERN = Pattern.compile("#\\{json:("+EXPRESSION_REGEX+INDEX_REGEX+"?)"+DEFAULT_VALUE_REGEX+"\\}");
    @Override
    protected String getExpressionRegex() {
        return EXPRESSION_REGEX;
    }

    protected String convertValue(String originValue,String jsonString) throws JBeerException {
        ReadContext docContext = JsonPath.parse(jsonString);
        List<FillerRule> rules =  generateFillerRule(JSON_FILLER_PATTERN,originValue);
        if(rules==null||rules.size()==0){
            return originValue;
        }
        String[] args = new String[rules.size()];
        for(int i=0;i<rules.size();i++){
            FillerRule rule = rules.get(i);
            try{
                if(rule.getIndex()!=null){
                    List<Object> jsonArray = docContext.read(rule.getExpression());
                    Object jsonObject = jsonArray.get(rule.getIndex());
                    if(Map.class.isAssignableFrom(jsonObject.getClass())){
                        args[i]= JSON.writeToJson(jsonObject);
                    }else{
                        args[i]=jsonObject.toString();
                    }
                }else{
                    Object jsonObject = docContext.read(rule.getExpression());
                    if(Map.class.isAssignableFrom(jsonObject.getClass())){
                        args[i]= JSON.writeToJson(jsonObject);
                    }else{
                        args[i]=jsonObject.toString();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                args[i]="\"\"";
            }
        }
        originValue = JSON_FILLER_PATTERN.matcher(originValue).replaceAll("%s");
        return String.format(originValue,args);
    }

    @Override
    protected String generateDataSource(FilterContext context) throws IOException, JBeerException {
        return context.getLastResponse().getResponseContent();
    }

    public static void main(String[] args) throws JBeerException {
        String content="{\"name\":#{json:'$..book[?(@.price <= $['expensive'])]'},\"age\":\"#{json:'$.store.book[*].category'[0]}\"}";

        String value = "{" +
                "    \"store\": {" +
                "        \"book\": [" +
                "            {" +
                "                \"category\": \"reference\"," +
                "                \"author\": \"Nigel Rees\"," +
                "                \"title\": \"Sayings of the Century\"," +
                "                \"price\": 8.95" +
                "            }," +
                "            {" +
                "                \"category\": \"fiction\"," +
                "                \"author\": \"Evelyn Waugh\"," +
                "                \"title\": \"Sword of Honour\"," +
                "                \"price\": 12.99" +
                "            }," +
                "            {" +
                "                \"category\": \"fiction\"," +
                "                \"author\": \"Herman Melville\"," +
                "                \"title\": \"Moby Dick\"," +
                "                \"isbn\": \"0-553-21311-3\"," +
                "                \"price\": 8.99" +
                "            }," +
                "            {" +
                "                \"category\": \"fiction\"," +
                "                \"author\": \"J. R. R. Tolkien\"," +
                "                \"title\": \"The Lord of the Rings\"," +
                "                \"isbn\": \"0-395-19395-8\"," +
                "                \"price\": 22.99" +
                "            }" +
                "        ]," +
                "        \"bicycle\": {" +
                "            \"color\": \"red\"," +
                "            \"price\": 19.95" +
                "        }" +
                "    }," +
                "    \"expensive\": 10" +
                "}";
        System.out.println(value.trim());
        System.out.println(JSON.writeToJson(JSON.readOriginJsonData(value)));
        value=JSON.writeToJson(JSON.readOriginJsonData(value));
        Matcher matcher = JSON_FILLER_PATTERN.matcher(content);
        //System.out.println(matcher.matches());
        while(matcher.find()){
            System.out.println(matcher.group());
        }

        JSONFiller jsonFiller = new JSONFiller();
        System.out.println(jsonFiller.convertValue(content,value));

    }
}
